package com.dev.view.common.adapter;

import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * @param <T>
 */
public abstract class CommonBaseAdapter<T> extends BaseAdapter {

    public List<T> list = new ArrayList<>();
    public Context context;
    public LayoutInflater inflater;

    public CommonBaseAdapter(Context context) {
        this.context = context;
        inflater = LayoutInflater.from(context);
    }

    public List<T> getmData() {
        return list;
    }

    public void addAllData(List<T> data) {
        if (data != null) {
            list.addAll(data);
        }
        notifyDataSetChanged();
    }

    public void clearData() {
        list.clear();
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return list != null ? list.size() : 0;
    }

    @Override
    public T getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    /**
     * @param position
     * @param convertView
     * @param parent
     * @return
     */
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        T t = getItem(position);
        View v;
        if (convertView == null) {
            v = newView(context, t, convertView, parent);
        } else {
            v = convertView;
        }
        bindView(position, v, t);
        return v;
    }

    /**
     * 小伙直接  COYP 吧
     * convertView = inflateView(R.layout.XXX);
     * ViewHold viewHold = new ViewHold(convertView);
     * convertView.setTag(viewHold);
     * return convertView;
     *
     * @param context
     * @param t
     * @param convertView
     * @param parent
     * @return
     */
    public abstract View newView(Context context, T t, View convertView, ViewGroup parent);

    /**
     * @param position
     * @param convertView
     * @param t
     * @COYP ViewHold viewHold = (ViewHold) convertView.getTag();
     */
    public abstract void bindView(int position, View convertView, T t);

    public View inflateView(int viewSoureId) {
        return inflater.inflate(viewSoureId, null);
    }

    public Resources getResources() {
        return context.getResources();
    }

}
